var question = "";
var reponses = "";
var checkReponses = [];
var existingReponsesEventuellesForQuestion = [];
var allReponsesEventuelles = [];

function getParameterByName(name)
{
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
  var regexS = "[\\?&]" + name + "=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(window.location.search);
  if(results == null)
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
}

function addReponseToQuestion(){
	
	while (checkReponses.length > 0) {
		checkReponses.pop();
	}
	
	$("input:checked").each(function(){
		checkReponses.push($(this).val());
	});
	
	if (checkReponses.length > 1){
		jCheckReponses = JSON.stringify(checkReponses);
		
		var data = {
			idQuestion : getParameterByName("idQuestion"),
			idReponses : jCheckReponses
		};
		
		$.ajax({
			type : 'Post',
			url : '/qRH-WS/services/question/addReponsesEventuelles',
			async: false,
			dataType : 'json',
			data : JSON.stringify(data),
			crossDomain : true,
			success : function(result, textStatus, jqXHR) {
				if(result != null){
					question = result;
					window.location.replace("addReponseCorrecteToQuestion.html?idQuestion="+question.idQuestion);
				} else {
					alert("Une erreur est survenue lors de la sauvegarde des reponses eventuelles");
				}
					
			},
			error : function(xhr, ajaxOptions, thrownError) {
				alert(xhr.status);
				alert(xhr.responseText);
			}
		});
	} else {
		alert("Veuillez selectionner au moins deux reponses eventuelles pour cette question");
	}
}


$(document).ready(
	function(){
		
		var txtIdReponse = $("#txtIdReponse");
		var txtContenuReponse = $("#txtContenuReponse");
		var sErrMsg = $("#sErrMsg");
		var allFields= $([]).add(txtIdReponse).add(txtContenuReponse).add(sErrMsg);
		
		var pCreateReponse =  $("#pCreateReponse");
		pCreateReponse.click(
			function() {
				openDialog();
	        }
		);
		
		function openDialog(){
			$('#dialog').dialog('open');
		}
		
		var data = {
			idQuestion : getParameterByName("idQuestion")
		};
		$.ajax({
			type : 'Get',
			url : '/qRH-WS/services/question/getQuestionById',
			async: false,
			dataType : 'json',
			data : data,
			crossDomain : true,
			success : function(result, textStatus, jqXHR) {
				question = result;
				var parent = $('aside > article > hgroup ');
				$('<h3>').text(question.contenuQuestion).appendTo(parent);
				existingReponsesEventuellesForQuestion = eval(question.reponsesEventuelles);
			},
			error : function(xhr, ajaxOptions, thrownError) {
				alert(xhr.status);
				alert(xhr.responseText);
			}
		});
		
		$.ajax({
			type : 'Get',
			url : '/qRH-WS/services/reponse/getAll',
			async: false,
			dataType : 'json',
			crossDomain : true,
			success : function(result, textStatus, jqXHR) {
				allReponsesEventuelles = eval(result);
			},
			error : function(xhr, ajaxOptions, thrownError) {
				alert(xhr.status);
				alert(xhr.responseText);
			}
		});
		
		var chkReponses = $('#chkReponses');

		for(var i = 0; i < allReponsesEventuelles.length; i++){
			put = false;
			for(var j = 0; j < existingReponsesEventuellesForQuestion.length; j++){
				if(allReponsesEventuelles[i].idReponse ==  existingReponsesEventuellesForQuestion[j].idReponse){
					$('<input type="checkbox" checked="checked" />').val(allReponsesEventuelles[i].idReponse).attr("id","chk"+allReponsesEventuelles[i].idReponse).appendTo(chkReponses);
					put = true;
				}
			}
			if(put === false){
				$('<input type="checkbox" />').val(allReponsesEventuelles[i].idReponse).attr("id","chk"+allReponsesEventuelles[i].idReponse).appendTo(chkReponses);
			}
			$('<label for="chk'+allReponsesEventuelles[i].idReponse+'" />').text(allReponsesEventuelles[i].contenuReponse).appendTo(chkReponses);
			$('<br/>').appendTo(chkReponses);
		}
		
		$("#dialog").dialog({
			bgiframe: true,
			autoOpen: false,
			height: 320,
			width:300,
			modal: true,
			buttons: {
				'Sauvegarder': function() {
					if(txtContenuReponse.val().length > 0){
						var reponse = {
							idReponse : txtIdReponse.val(),
							contenuReponse: txtContenuReponse.val(),
					    };
						$.ajax({
							type : 'GET',
							url : '/qRH-WS/services/reponse/create',
							data : reponse,
							dataType : 'json',
							success : function(result, textStatus, jqXHR) {
								console.log('Success');
								location.reload();
							}
						});
						$(this).dialog('close');
					} else {
						sErrMsg.text("Veuillez saisir le contenu de la question");
					}
					
				},
				Cancel: function() {
					$(this).dialog('close');
				}
			},
			close: function() {
				allFields.val('').removeClass('ui-state-error');
			}
		});
		
}
);